package com.lightsh.body;

import org.jbox2d.collision.shapes.CircleDef;
import org.jbox2d.collision.shapes.CircleShape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.World;

import com.lightsh.utility.GeometryUtility;

import android.graphics.Canvas;
import android.graphics.Rect;

/**
 * 一个圆形的物体,该物体使用的单位为meter
 * @author Light
 */
public class Circle extends PhysicsBody{	
	
	protected CircleDef mCircleDef;
	public Circle(World world, float x, float y, float radius, float density, float friction, float restitution, boolean bullet){
		super(world);		
		mCircleDef = new CircleDef();
		mCircleDef.radius = radius;
		mCircleDef.density = density;
		mCircleDef.friction = friction;
		mCircleDef.restitution = restitution;
		mBodyDef.position.x = x;
		mBodyDef.position.y = y;
		mBodyDef.isBullet = bullet;
	}

	@Override
	public void draw(Canvas canvas, Rect screenRect, float selfScale, float worldScale) {
		super.draw(canvas, screenRect, selfScale, worldScale);
		
		if(isInRect(screenRect, selfScale)){
			Vec2 vec2 = getPosition();
			canvas.save();
			rotateCanvas(canvas, mBody.getAngle(), vec2, screenRect, selfScale, worldScale);
			if(mSprite != null){
				mSprite.draw(canvas, mPaint, (int)((vec2.x - mCircleDef.radius) / selfScale + mDrawImageOffsetX - screenRect.left), 
						(int)((vec2.y - mCircleDef.radius) / selfScale + mDrawImageOffsetY - screenRect.top), worldScale);
			} else if(mBitmap != null){
				drawBitmap(canvas, vec2.x - mCircleDef.radius, vec2.y - mCircleDef.radius, screenRect, selfScale, worldScale);
			}else{
				canvas.drawCircle((vec2.x / selfScale - screenRect.left) * worldScale, (vec2.y / selfScale - screenRect.top) * worldScale, 
						mCircleDef.radius / selfScale * worldScale, mPaint);
			}
			canvas.restore();
		}
	}

	@Override
	public void update() {
		super.update();
	}

	@Override
	public boolean isInRect(Rect rect, float selfScale) {
		Vec2 vec2 = getPosition();
		CircleShape shape = (CircleShape) mShape;
		
		return GeometryUtility.isCircleInRect(vec2, shape.m_radius, rect, selfScale);
	}
	@Override
	public void create() {
		super.create();
		mBody = mWorld.createBody(mBodyDef);
		mShape = mBody.createShape(mCircleDef);
		mBody.setMassFromShapes();
		super.applyAction();
	}
	
	
}
